/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package mobi.smarthosts;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

/**
 * This Activity handles "editing" hosts, where editing is responding to
 * {@link Intent#ACTION_VIEW} (request to view data), edit a note
 * {@link Intent#ACTION_EDIT} from {@link #EXTRA_FILE_PATH}.
 */
public class HostsEditorActivity extends Activity {

    public static final String EXTRA_FILE_PATH = "file_path";

    public static final int DIALOG_SAVE = 0;

    private String mFilePath;
    private String mOriginalContent;
    private EditText mText;
    private boolean mNeedReboot;

    /**
     * Defines a custom EditText View that draws lines between each line of text that is displayed.
     */
    public static class LinedEditText extends EditText {
        private Rect mRect;
        private Paint mPaint;

        public LinedEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(0x800000FF);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            int count = getLineCount();
            Rect r = mRect;
            Paint paint = mPaint;

            for (int i = 0; i < count; i++) {
                int baseline = getLineBounds(i, r);
                canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
            }

            super.onDraw(canvas);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editor);

        mFilePath = getIntent().getStringExtra(EXTRA_FILE_PATH);
        mOriginalContent = ShellExecutor.rootReadFile(mFilePath);
        mText = (EditText) findViewById(R.id.view_editor);
        mText.setText(mOriginalContent);
    }

    protected Dialog onCreateDialog(int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        switch (id) {
        case DIALOG_SAVE:
            builder.setMessage(R.string.msg_saveConfirmation)
                   .setIcon(android.R.drawable.ic_dialog_alert)
                   .setCancelable(false)
                   .setPositiveButton(R.string.label_yes, mSaveDialogListener)
                   .setNeutralButton(R.string.label_no, mSaveDialogListener)
                   .setNegativeButton(R.string.label_cancel, mSaveDialogListener);
            return builder.create();

        default:
            return super.onCreateDialog(id);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // shield search key
        if (keyCode == KeyEvent.KEYCODE_SEARCH) return true;

        // validate if content is changed or not.
        if (keyCode == KeyEvent.KEYCODE_BACK
                && mOriginalContent != null
                && !mOriginalContent.equals(mText.getText().toString())) {
            showDialog(DIALOG_SAVE);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.editor_options_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        String content = mText.getText().toString();
        menu.findItem(R.id.menu_revert).setVisible(!mOriginalContent.equals(content));
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_save:
            updateHosts();
            break;
        case R.id.menu_cancel:
            cancelEdit();
            break;
        case R.id.menu_revert:
            cancelEdit();
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateHosts() {
        String content = mText.getText().toString();
        if (content.equals(mOriginalContent)) return;

        try {
            ShellExecutor.rootWriteFile(mFilePath, content, false);
        } catch (Exception e) {
            ViewHelper.showAlertDialog(this,
                    getString(R.string.title_error),
                    getString(R.string.error_cannotSaveEdit, e.getMessage()),
                    getString(R.string.label_ok), null);
        }

        mNeedReboot = mFilePath.equals(Configuration.HOSTS_SYSTEM.getAbsolutePath());
        mOriginalContent = mText.getText().toString();
    }

    private void cancelEdit() {
        mText.setText(mOriginalContent);
        finish();
    }

    protected DialogInterface.OnClickListener mSaveDialogListener =
            new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                updateHosts();
                if (mNeedReboot) Toast.makeText(HostsEditorActivity.this, R.string.msg_reboot, Toast.LENGTH_SHORT).show();
                else finish();
                break;
            case DialogInterface.BUTTON_NEUTRAL:
                cancelEdit();
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                break;
            default:
            }
            dialog.cancel();
        }
    };
}
